using System;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Xml;

namespace SMS.CDR
{
    public class ConfigSettings
    {
        // Methods
        private ConfigSettings() { }

        private static string GetConfigFilePath()
        {
            return (Assembly.GetExecutingAssembly().Location + ".config");
        }

        private static XmlDocument LoadConfigDocument()
        {
            XmlDocument doc1 = null;
            XmlDocument doc2;
            try
            {
                doc1 = new XmlDocument();
                doc1.Load(GetConfigFilePath());
                doc2 = doc1;
            }
            catch (FileNotFoundException ex)
            {
                throw new Exception("No configuration file found.", ex);
            }
            return doc2;
        }

        public static string ReadSetting(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }

        public static void RemoveSetting(string key)
        {
            XmlDocument document = LoadConfigDocument();
            XmlNode node = document.SelectSingleNode("//appSettings");
            try
            {
                if (node == null)
                    throw new InvalidOperationException("appSettings section not found in config file.");

                node.RemoveChild(node.SelectSingleNode(string.Format("//add[@key='{0}']", key)));
                document.Save(GetConfigFilePath());
            }
            catch (NullReferenceException ex)
            {
                throw new Exception(string.Format("The key {0} does not exist.", key), ex);
            }
        }

        public static void WriteSetting(string key, string value)
        {
            XmlDocument doc = LoadConfigDocument();
            XmlNode node = doc.SelectSingleNode("//appSettings");
            if (node == null)
                throw new InvalidOperationException("appSettings section not found in config file.");

            try
            {
                XmlElement newChild = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
                if (newChild != null)
                    newChild.SetAttribute("value", value);

                else
                {
                    newChild = doc.CreateElement("add");
                    newChild.SetAttribute("key", key);
                    newChild.SetAttribute("value", value);
                    node.AppendChild(newChild);
                }
                doc.Save(GetConfigFilePath());
            }
            catch { }
        }
    }
}

